<template>
  <!-- 传送到body 解决z-index问题 -->
  <div class="vertical-feed" ref="feedContainer">
    <!-- 导航栏 -->
    <Navbar>
      <template #left>
        <div class="back-btn" @click="handleBack">
          <Icon name="zuojiantou" color="#fff" size="18"></Icon>
        </div>
      </template>
    </Navbar>
    <div class="feed-container" :style="{ transform: `translateY(${translateY}px)` }"
      @touchstart.passive="handleTouchStart" @touchmove.passive="handleTouchMove" @touchend.passive="handleTouchEnd">
      <div v-for="(item, index) in videoListWithLikeStatus" :key="item.videoId || index" class="feed-item">
        <!-- 视频区域 -->
        <div class="video-container" @click="handleVideoClick($event, index)">
          <!-- 自己播放并且 无线循环 -->
          <video ref="videoRefs" class="media-video"
            :src="item.videoPath || 'http://video.pearvideo.com/mp4/third/20181203/cont-1486048-10194271-192843-hd.mp4'"
            preload="metadata" playsinline webkit-playsinline x5-playsinline loop :muted="false"></video>
          <!-- 播放/暂停覆盖层 -->
          <div v-if="videoStates[index] === 'paused'" class="play-overlay">
            <Icon name="zantingtubiao" color="#fff" size="32" />
          </div>
        </div>

        <!-- 左侧信息 -->
        <div class="left-info">
          <div class="username">@{{ item.userNickname || '用户名' }}</div>
          <div class="description">{{ item.videoDesc || '视频描述' }}</div>
          <div class="music-info">
            <span class="music-icon">♪</span>
            {{ item.music || '原声' + (index + 1) }}
          </div>
        </div>

        <!-- 右侧互动按钮 -->
        <div class="right-actions">
          <div class="action-item">
            <div class="avatar">
              <img :src="item.userAvatar" alt="用户头像" />
            </div>
          </div>
          <div class="action-item" @click.stop="handleLike(item.videoId)">
            <div class="action-icon">
              <Icon name="xin-2" :color="item.isLiked ? '#ff2442' : '#fff'" size="28"></Icon>
            </div>
            <div class="action-count">{{ item.likeNum || 0 }}</div>
          </div>
          <div class="action-item" @click.stop="handleComment(item.videoId)">
            <div class="action-icon">
              <Icon name="pinglun" color="#fff" size="28"></Icon>
            </div>
            <div class="action-count">{{ item.commentNum || 0 }}</div>
          </div>
          <div class="action-item" @click.stop="handleShare(index)">
            <div class="action-icon">
              <Icon name="a-fenxiangweifenxiang" color="#fff" size="24"></Icon>
            </div>
            <div class="action-count">{{ item.shareNum || 0 }}</div>
          </div>
        </div>
        <!-- 输入框区域 -->
        <div class="comment-input">
          <!-- 获焦事件 -->
          <input type="text" @focus="handleComment(item.videoId)" placeholder="有爱评论，说点儿好听的~" />
          <div class="send-icons">
            <Icon name="aite" color="#fff" size="20" @click="handleComment(item.videoId)"></Icon>
            <Icon name="dui" color="#fff" size="20" @click="handleComment(item.videoId)"></Icon>
          </div>
        </div>
      </div>
    </div>
    <!-- 评论弹窗 -->
    <CommentModal v-if="showCommentModal" v-model="showCommentModal" :videoId="videoCommentsVideoId" />

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick, defineAsyncComponent } from 'vue';
import Navbar from './Navbar.vue';
import Icon from './Icon.vue'
import { useUserStore } from '@/stores/userinfo'
const userStore = useUserStore()
const { userId } = userStore.userInfo

// 视频点赞状态
import { getVideoLikeStatusAPI, postVideoLikeAPI } from '@/api/my'

// 定义props
const props = defineProps({
  feedData: {
    type: Array,
    default: () => []
  },
  currentIndex: {
    type: Number,
    default: 0
  }
});
const model = defineModel()

// 定义emits
const emit = defineEmits(['update:currentIndex', 'like', 'comment', 'share']);

// 响应式数据
const feedContainer = ref(null);
const itemHeight = ref(0);
const translateY = ref(0);
const startY = ref(0);
const currentY = ref(0);
const isDragging = ref(false);
const startIndex = ref(0);
const startTime = ref(0);
const lastTime = ref(0);
const lastY = ref(0);
const velocity = ref(0);
const isAnimating = ref(false);
const animationFrameId = ref(null);
const initialTouchX = ref(0);
const initialTouchY = ref(0);

// 存储带有点赞状态的视频数据
const videoListWithLikeStatus = ref([]);

// 根据接受的feedData进行循环请求根据每一项的videoId 求出点赞状态
const fetchLikeStatusAndMergeData = async () => {
  try {
    // 使用用户store中的userId
    const currentUserId = userId || 1;

    // 为每个视频请求点赞状态
    const promises = props.feedData.map(async (video) => {
      try {
        const likeStatus = await getVideoLikeStatusAPI(currentUserId, video.videoId);
        // 将点赞状态合并到视频数据中
        return {
          ...video,
          isLiked: likeStatus.data || false
        };
      } catch (error) {
        console.error(`获取视频${video.videoId}点赞状态失败:`, error);
        // 如果请求失败，默认为未点赞
        return {
          ...video,
          isLiked: false
        };
      }
    });

    // 等待所有请求完成
    const results = await Promise.all(promises);
    videoListWithLikeStatus.value = results;
  } catch (error) {
    console.error('获取点赞状态失败:', error);
    // 如果整体失败，使用原始数据
    videoListWithLikeStatus.value = props.feedData.map(video => ({
      ...video,
      isLiked: false
    }));
  }
};

// 计算当前应该显示的索引
const activeIndex = computed({
  get: () => props.currentIndex,
  set: (value) => emit('update:currentIndex', value)
});

// 本地索引变量，用于内部状态管理
const localIndex = ref(props.currentIndex);

// 监听currentIndex变化，更新本地索引
watch(activeIndex, (newIndex, oldIndex) => {
  // 只有在非拖动、非动画状态下，且索引确实发生变化时才更新位置
  if (!isDragging.value && !isAnimating.value && newIndex !== oldIndex) {
    localIndex.value = newIndex;
    translateY.value = -newIndex * itemHeight.value;
    console.log(`监听器更新位置: 索引${newIndex}, translateY=${translateY.value}`);
  }
});

// 监听feedData变化，重新计算高度和获取点赞状态
watch(() => props.feedData, () => {
  nextTick(() => {
    calculateItemHeight();
    fetchLikeStatusAndMergeData();
  });
}, { deep: true });

// 计算每个项目的高度
const calculateItemHeight = () => {
  if (feedContainer.value) {
    itemHeight.value = feedContainer.value.clientHeight;
    translateY.value = -localIndex.value * itemHeight.value;
  }
};
// 触摸事件处理
const handleTouchStart = (e) => {
  // 取消任何正在进行的动画
  if (animationFrameId.value) {
    cancelAnimationFrame(animationFrameId.value);
    animationFrameId.value = null;
  }

  startY.value = e.touches[0].clientY;
  currentY.value = startY.value; // 初始化currentY
  lastY.value = startY.value;
  startTime.value = Date.now();
  lastTime.value = startTime.value;
  startIndex.value = localIndex.value;
  isDragging.value = false; // 初始状态不认为是拖动
  isAnimating.value = false;
  velocity.value = 0;

  // 记录初始位置，用于判断是否是垂直滑动
  initialTouchX.value = e.touches[0].clientX;
  initialTouchY.value = e.touches[0].clientY;
};

const handleTouchMove = (e) => {
  currentY.value = e.touches[0].clientY;
  const currentTime = Date.now();
  const deltaTime = currentTime - lastTime.value;

  // 计算移动距离
  const deltaX = Math.abs(e.touches[0].clientX - initialTouchX.value);
  const deltaY = Math.abs(currentY.value - initialTouchY.value);
  const moveThreshold = 10; // 移动阈值，超过这个值才认为是拖动

  // 如果是水平滑动或者移动距离未超过阈值，不处理
  if (deltaX > deltaY || deltaY < moveThreshold) {
    return;
  }

  // 如果移动距离超过阈值，标记为拖动
  if (!isDragging.value) {
    isDragging.value = true;
  }

  // 计算速度
  if (deltaTime > 0) {
    velocity.value = (currentY.value - lastY.value) / deltaTime;
  }

  const diff = currentY.value - startY.value;

  // 限制滑动范围
  const maxTranslate = -(props.feedData.length - 1) * itemHeight.value;
  const minTranslate = 0;

  let newTranslateY = -startIndex.value * itemHeight.value + diff;

  // 添加更自然的阻力效果
  const resistance = 0.3;
  if (newTranslateY > minTranslate) {
    newTranslateY = minTranslate + Math.pow(newTranslateY - minTranslate, resistance) * Math.sign(newTranslateY - minTranslate);
  } else if (newTranslateY < maxTranslate) {
    newTranslateY = maxTranslate - Math.pow(maxTranslate - newTranslateY, resistance) * Math.sign(maxTranslate - newTranslateY);
  }

  translateY.value = newTranslateY;

  lastY.value = currentY.value;
  lastTime.value = currentTime;
};

const handleTouchEnd = () => {
  // 如果没有实际拖动，不处理滑动逻辑
  if (!isDragging.value) {
    return;
  }

  isDragging.value = false;

  const currentTime = Date.now();
  const deltaTime = currentTime - lastTime.value;

  // 计算最终速度（转换为像素/秒）
  if (deltaTime > 0) {
    velocity.value = (currentY.value - lastY.value) / deltaTime * 1000;
  }

  const diff = currentY.value - startY.value;

  // 判断是否应该切换到下一个或上一个
  const threshold = itemHeight.value * 0.25; // 调整滑动阈值，增加阈值使切换更明确

  let newIndex = startIndex.value;

  // 基于滑动距离和速度判断是否切换
  // 速度阈值调整为300像素/秒
  if (Math.abs(diff) > threshold || Math.abs(velocity.value) > 300) {
    if (diff > 0 && startIndex.value > 0) {
      // 向下滑动，显示上一个
      newIndex = startIndex.value - 1;
    } else if (diff < 0 && startIndex.value < props.feedData.length - 1) {
      // 向上滑动，显示下一个
      newIndex = startIndex.value + 1;
    }
  }

  console.log(`滑动结束: startIndex=${startIndex.value}, newIndex=${newIndex}, diff=${diff}, velocity=${velocity.value}, threshold=${threshold}`);

  // 使用动画平滑过渡到目标位置
  animateToIndex(newIndex);
};

// 平滑动画到指定索引
const animateToIndex = (targetIndex) => {
  console.log(`开始动画: 从索引${localIndex.value}到${targetIndex}`);

  isAnimating.value = true;

  const targetY = -targetIndex * itemHeight.value;
  const startY = translateY.value;
  const distance = targetY - startY;
  const duration = Math.min(300, Math.max(150, Math.abs(distance) * 0.3)); // 动态计算动画时长

  const startTime = performance.now();

  const animate = (currentTime) => {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);

    // 使用缓动函数使动画更自然
    const easeOutQuart = 1 - Math.pow(1 - progress, 4);
    translateY.value = startY + distance * easeOutQuart;

    if (progress < 1) {
      animationFrameId.value = requestAnimationFrame(animate);
    } else {
      // 动画结束时更新状态
      // 确保translateY值正确设置
      translateY.value = targetY;
      // 先更新本地索引
      localIndex.value = targetIndex;
      // 然后清除动画状态
      isAnimating.value = false;
      animationFrameId.value = null;
      // 最后更新父组件的索引
      activeIndex.value = targetIndex;
      console.log(`动画结束: 当前索引已更新为${localIndex.value}`);
    }
  };

  animationFrameId.value = requestAnimationFrame(animate);
};

// 互动事件处理
const handleLike = async (videoId) => {
  const res = await postVideoLikeAPI(userId, videoId)
  if (res.code === 200) {
    // 点赞成功，更新点赞状态
    console.log(videoListWithLikeStatus.value)
    const video = videoListWithLikeStatus.value.find(v => v.videoId === videoId)
    video.isLiked = !video.isLiked
    // 更新点赞数
    if (video.isLiked) {
      video.likeNum = (video.likeNum || 0) + 1
    } else {
      video.likeNum = Math.max(0, (video.likeNum || 0) - 1)
    }
  }
};


// 评论弹窗
const showCommentModal = ref(false)
const videoCommentsVideoId = ref('')
const CommentModal = defineAsyncComponent(() => import('@/components/common/CommentModal.vue'))
const handleComment = (videoId) => {
  console.log(videoId)
  videoCommentsVideoId.value = videoId
  showCommentModal.value = true
};
const handleShare = (index) => {
  emit('share', index);
};

// 组件挂载后计算高度和获取点赞状态
onMounted(() => {
  nextTick(() => {
    const tabbar = document.querySelector('.tabbar')
    if (tabbar) {
      tabbar.style.visibility = 'hidden'
    }
    calculateItemHeight();
    fetchLikeStatusAndMergeData();
  });
});

// 组件卸载时清理动画帧
onUnmounted(() => {
  if (animationFrameId.value) {
    cancelAnimationFrame(animationFrameId.value);
  }
});
const handleBack = () => {
  model.value = false
  const tabbar = document.querySelector('.tabbar')
  if (tabbar) {
    tabbar.style.visibility = 'visible'
  }
}
// 处理视频点击事件，确保只有点击视频本身时才触发播放/暂停
const handleVideoClick = (event, index) => {
  // 检查点击的元素是否是视频元素或者是视频容器的直接子元素
  const isVideoElement = event.target.tagName === 'VIDEO';
  const isPlayOverlay = event.target.closest('.play-overlay');

  // 检查点击的元素是否在右侧互动按钮区域
  const isRightActions = event.target.closest('.right-actions');

  // 检查点击的元素是否在左侧信息区域
  const isLeftInfo = event.target.closest('.left-info');

  // 检查点击的元素是否在评论输入框区域
  const isCommentInput = event.target.closest('.comment-input');

  // 只有当点击的是视频元素或播放覆盖层，且不在其他UI元素上时，才触发播放/暂停
  if ((isVideoElement || isPlayOverlay) && !isRightActions && !isLeftInfo && !isCommentInput) {
    togglePlay(index);
  }
};

// 切换播放/暂停
const videoStates = ref({})
const videoRefs = ref([])

const togglePlay = async (index) => {
  const video = videoRefs.value[index]
  if (!video) return

  const currentState = videoStates.value[index] || 'idle'

  if (currentState === 'playing') {
    // 播放 → 暂停
    video.pause()
    videoStates.value[index] = 'paused'
  } else {
    // 暂停 或 idle → 播放
    // 暂停所有其他视频，并重置为 idle（隐藏图标）
    videoRefs.value.forEach((v, i) => {
      if (v && i !== index) {
        v.pause()
        videoStates.value[i] = 'idle'
      }
    })

    try {
      await video.play()
      videoStates.value[index] = 'playing'
    } catch (err) {
      console.warn('播放失败:', err)
      videoStates.value[index] = 'idle'
    }
  }
}
</script>

<style lang="scss" scoped>
.vertical-feed {
  @include fixed-top;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #000;
  z-index: 10000;
}

.feed-container {
  height: 100%;
  will-change: transform;
}

.feed-item {
  position: relative;
  height: 100vh;
  width: 100%;

  .comment-input {
    width: 100%;
    padding: 14px;
    background-color: #161622;
    color: #fff;
    font-size: 14px;
    display: flex;
    gap: 8px;
    @include absolute-bottom-left;
    z-index: 10000;

    input {
      width: 100%;
      height: 100%;
      background-color: transparent;
    }

    .send-icons {
      width: 80px;
      @include flex-around;
      @include absolute-bottom-right(10px, 16px);

    }
  }
}

.video-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000;

  .play-overlay {
    width: 100%;
    height: 100%;
    @include absolute-top-right;
    @include flex-center;
  }

  video {
    width: 100%;
    height: 100%;
  }

}

.left-info {
  position: absolute;
  bottom: 60px;
  left: 20px;
  color: #fff;
  max-width: 70%;
  z-index: 20;
  /* 提高z-index，确保信息在视频上层 */
  pointer-events: none;
  /* 防止信息区域影响视频点击事件 */

  .username {
    font-weight: bold;
    font-size: 18px;
    margin-bottom: 8px;
  }

  .description {
    font-size: 14px;
    margin-bottom: 8px;
    line-height: 1.4;
  }

  .music-info {
    display: flex;
    align-items: center;
    font-size: 14px;

    .music-icon {
      margin-right: 5px;
    }
  }
}

.right-actions {
  position: absolute;
  bottom: 60px;
  right: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 20;
  /* 提高z-index，确保按钮在视频上层 */

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    cursor: pointer;
    pointer-events: auto;
    /* 确保按钮可以接收点击事件 */

    .avatar {
      width: 45px;
      height: 45px;
      border-radius: 50%;
      overflow: hidden;
      border: 2px solid #fff;
    }

    .action-icon {
      font-size: 28px;
      margin-bottom: 5px;
    }

    .action-count {
      color: #fff;
      font-size: 12px;
      text-align: center;
    }
  }
}
</style>